package src.CodeTopSecondPractice;

import java.util.Random;

public class _912 {
    public int[] sortArray(int[] nums) {
        QuickSort(nums, 0, nums.length - 1);
        return nums;
    }

    // 普通快排
    public static void QuickSort(int[] nums, int low, int high) {
        int i, j, temp, middle;
        if (low > high) {
            return;
        }
        i = low;
        j = high;
        temp = nums[low];
        while (i < j) {
            while (nums[j] >= temp && (i < j)) {
                j--;
            }
            while (nums[i] <= temp && (i <j)) {
                i++;
            }
            if (i < j) {
                middle = nums[i];
                nums[i] = nums[j];
                nums[j] = middle;
            }
        }
        nums[low] = nums[i];
        nums[i] = temp;
        QuickSort(nums, low, j - 1);
        QuickSort(nums, j + 1, high);
    }

    // 随机选取主元快排
    public static void randomizedQuicksort(int[] nums, int left, int right) {
        if (left < right) {
            int pos = randomPartition(nums, left, right);
            randomizedQuicksort(nums, left, pos - 1);
            randomizedQuicksort(nums, pos + 1, right);
        }
    }

    public static int randomPartition(int[] nums, int left, int right) {
        int i = new Random().nextInt(right - left + 1) + left;
        swap(nums, i, right);
        return Partition(nums, left, right);
    }

    public static int Partition(int[] nums, int left, int right) {
        // 将基准保存为副本
        int pivot = nums[right];
        // 记录大于基准值的第一个指针
        int i = left - 1;
        // 遍历调整数值
        for (int j = left ; j <= right - 1 ; j++) {
            if (nums[j] <= pivot) {
                i = i + 1;
                swap(nums, i, j);
            }
        }
        swap(nums, i + 1, right);
        return i + 1;
    }

    // 交换元素
    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
